package cn.wolfcode.web.modules.customerapp.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.CityUtils;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.customerapp.entity.TbCustomer;
import cn.wolfcode.web.modules.customerapp.service.ITbCustomerService;


import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 杨志海
 * @since 2023-06-27
 */
@Controller
@RequestMapping("/customerapp")
public class TbCustomerController extends BaseController {

    @Autowired
    private ITbCustomerService entityService;

    private static final String LogModule = "TbCustomer";

    @GetMapping("/list.html")
    public String list() {
        return "app/customerapp/list";
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('app:customerapp:add')")
    public ModelAndView toAdd(ModelAndView mv) {

        //携带 所有的省份 数据到页面
        mv.addObject("citys", CityUtils.citys);


        mv.setViewName("app/customerapp/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('app:customerapp:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("app/customerapp/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        mv.addObject("citys",CityUtils.citys);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('app:customerapp:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        //根据关键字进行模糊查询，分别查询，企业名称 customerName，法定代表人 legalLeader
        //通过关键字 parameterName 比较 customerName,legalLeader,进行模糊查询
        LambdaQueryChainWrapper<TbCustomer> wrapper = entityService.lambdaQuery();
        //告诉mybatis-plus 要如何查询
        //condition条件： 判定parameterName中是否为空，只有不为空的时侯，才需要做模糊查询
        wrapper.like(!StringUtils.isEmpty(parameterName),TbCustomer::getCustomerName,parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbCustomer::getLegalLeader,parameterName);
        page = wrapper.page(page);

        //把省份的信息 地区偏码（数字） 变为 文字
        List<TbCustomer> records = page.getRecords();
        for(TbCustomer record : records){
            String city_name = CityUtils.getCityValue(record.getProvince());//获取key对应的Value
            record.setProvince(city_name);//把Value覆盖key
        }


        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('app:customerapp:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustomer entity, HttpServletRequest request) {
        //1.设置录入时间
        entity.setInputTime(LocalDateTime.now());

        //2.录入人
        SysUser user = (SysUser) request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        entity.setInputUserId(user.getUserId());

        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('app:customerapp:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustomer entity) {
        //生成修改时间
        entity.setUpdateTime(LocalDateTime.now());
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('app:customerapp:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

}
